#-*- encoding: utf-8 -*-
'''
Created on 2013-02-06

@author: Liuxue
'''

from logging import getLogger
import json
import tornado.web
from uuid import uuid1

class BaseRequestHandler(tornado.web.RequestHandler):
    
    '''
    通用的请求基类
    继承自 tornado.web.RequestHandler
    提供get和post两种请求方式
    '''
    
    def prepare(self):
        try:
            self.logger = getLogger('tornado.application')
            
            self.uuid = str(uuid1())
            self.log_response = []
            paramestr = self.parse_request_param()
            req_log = self.request.uri + (' - %s'%paramestr if paramestr else '')
            self.logger.debug(req_log, extra={'trace': self.uuid})
        except Exception as e:
            self.finish('...')
            self.logger.warning(e, extra={'trace': self.uuid})
        
    def get(self):
        '''
        响应get请求
        '''
        pass

    def post(self):
        '''
        响应post请求
        '''
        self.get()
    
    def parse_request_param(self):
        args = self.request.arguments
        buf = []
        try:
            for k, v in list(args.items()):
                buf.append('%s=%s'%(k, ','.join(['%s'%s for s in v])))
        except Exception as e:
            self.logger.info('%s' % str(e), extra={'trace': self.uuid})
             
        return ' -- '.join(buf)
     
    def on_finish(self):
        try:
            self.log_response.append('%s'%self.request.request_time())
            self.logger.debug(' '.join(self.log_response), extra={'trace': self.uuid}) 
        except Exception as e:
            self.logger.warning('%s' % str(e), extra={'trace': self.uuid})
            
    def g(self, name, default=''):
        '''
        包裹get_argument
        '''
        res = self.get_argument(name, default)
        if res == '':
            res = default
        
        return res
        
    def __format_trunk(self, trunk):
        if isinstance(trunk, dict):
            ret = []
            for k,v in trunk.items():
                ret.append('%s:%s'%(k,v))
            return ','.join(ret)
        else:
            return trunk
        
    def write(self, trunk):
        self.log_response.append(self.__format_trunk(trunk))
        res = json.dumps(trunk, indent=2)
        tornado.web.RequestHandler.write(self, res)
        self.flush()

    def get_current_user(self):
        return '111'

from mako.lookup import TemplateLookup
from tornado.template import Template as TTemplate
class MakoHandler(tornado.web.RequestHandler):
    def prepare(self):
        getLogger('tornado.application').info(self.request)
        tornado.web.RequestHandler.prepare(self)
        self.require_setting('mako_templates_lookup')
        self._lookup = TemplateLookup(self.settings.get('mako_templates_lookup', []), #这里是模板的路径  这么设置它会在templates文件夹下查找模板
                                      encoding_errors='replace',
                                      input_encoding='utf-8',
                                      output_encoding='utf-8',)
        
    def render_string(self, filename, **kwargs):
        '''Override render_string to use mako template.
        
        Like tornado render_string method, this method
        also pass request handler environment to template engine.
        '''
        try:
            template = self._lookup.get_template(filename)
            env_kwargs = self.get_template_namespace()
            t0 = template.render(**kwargs)
            t = TTemplate(t0).generate(**env_kwargs)
            return t
        except Exception as e:
            # exception handler
            getLogger('tornado').exception(e)
        
    def get(self):
        self.render('demo_mako.html', title='mako')

